import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import AreaMap from '@/components/AreaMap/index';

import find from 'lodash/find';
import { renderValveOpen, renderSignalIntensity, afterCloseModal } from '@/utils/utils';
import EditDMA from './JoinDMA'
import debounce from 'lodash/debounce';
import BuildModalTitle from '@/components/BuildModalTitle';
import Detail from './Detail';
import AddOrEditMeter from './AddOrEditMeter';
import ReactDataGrid from 'react-data-grid';
import ImportMeter from './ImportMeter';
import AddMechanical from './AddMechanical'
import AddOneMechanical from './AddOneMechanical'
import AddOneMechanical2 from './AddOneMechanical2'
import request from '@/utils/request';

const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ meters, loading, global }) => ({
  meters,
  global,
  loading: loading.models.meters,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      meters: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        meters: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'meters/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'meters/changeLoaded',
          });
          dispatch({
            type: 'meters/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'meters/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'meters/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }
  handleImport=()=>{
    const formValues =this.importFormRef.props.form.getFieldsValue();
    const that=this;
    console.log('formValues',formValues)
    if(!formValues.file||formValues.file.fileList.length===0){
      message.error('请选择文件');
      return false
    }

    var formData = new FormData();
    formData.append("file", formValues.file.file);
    formData.append("protocol_id", formValues.protocol_id);
    formData.append("company_id", formValues.company_id);
    formData.append("start_row", formValues.start_row);
    formData.append("end_row", formValues.end_row);
    request(`/meter_files`, {
      method: 'POST',
      data: formData
    }).then((response)=> {
      console.log(response);
      if(response.status===200){
        message.success('批量导入水表成功')
        const {
          meters: { searchParams },
        } = that.props;
        that.setState({
          importModal:false
        })
        that.handleSearch(searchParams);

      }
    })
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'meters/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          meters: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      },
    });
  };
  renderSimpleForm() {
    const {
      meters: { searchParams },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    const username=sessionStorage.getItem('username')

    return (
      <Form layout="inline" className="search-form">
   {/*     {
          !sessionStorage.getItem('company_id')&&
          <FormItem label="所属分站">
            {getFieldDecorator('company_id', {
              initialValue: searchParams.company_id,
            })(
              <Select style={{ width: '120px' }} allowClear={true}>
                {
                  JSON.parse(sessionStorage.getItem('management_companies')).map((item,index)=>{
                    return <Option key={index} value={item.id}>
                      {item.name}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
        }*/}
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '120px' }} allowClear disabled={Boolean(username==='宁波水表'||username==='竞达水表'||username==='西安旌旗'||username==='泰安水表'||username==='泰安新贝水表')}>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表类型">
          {getFieldDecorator('communication_type', {
            initialValue: searchParams.communication_type,
          })(
            <Select style={{ width: '120px' }} allowClear >
              <Option  value={'1'}>远传水表</Option>
              <Option  value={'2'}>机械水表</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="是否已开户">
          {getFieldDecorator('opened_account', {
            initialValue: searchParams.opened_account,
          })(
            <Select style={{ width: '80px' }} allowClear >
              <Option  value={'1'}>已开户</Option>
              <Option  value={'-1'}>未开户</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="状态">
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(
            <Select style={{ width: '80px' }} allowClear>
              <Option  value={'1'}>正常</Option>
              <Option  value={'-1'}>停用</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="阀门状态">
          {getFieldDecorator('valve_status', {
            initialValue: searchParams.valve_status,
          })(
            <Select style={{ width: '80px' }} allowClear >
              <Option  value={'1'}>开启</Option>
              <Option  value={'-1'}>关闭</Option>
              <Option  value={'2'}>未上报</Option>
              <Option  value={'3'}>异常</Option>
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="安装地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="IMEI">
          {getFieldDecorator('imei', {
            initialValue: searchParams.imei,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
    {/*    <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        meters: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }
  handleAddMechanical=()=>{
    const formValues = this.addMechanicalFormRef.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    const metersArr=[]
    for(let i=0;i<meterskey.length;i++){
      if(formValues[`meter_number-${meterskey[i]}`]){
        metersArr.push({
          meter_number:formValues[`meter_number-${meterskey[i]}`],
          value:formValues[`meter_value-${meterskey[i]}`],
          date:moment(formValues[`meter_date-${meterskey[i]}`]).format('YYYY-MM-DD'),
        })
      }

    }
    console.log('metersArr',metersArr);
    const that=this;
    this.props.dispatch({
      type: 'meters/addValue1',
      payload: {
        company_id:formValues.company_id,
        metersArr
      },
      callback() {
        message.success('手工抄表成功');
        // that.setState({
        //   addMechanicalModal: false,
        // });
      },
    });
  }
  handleAddOneMechanical=()=>{
    const formValues = this.addOneMechanicalFormRef.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    console.log('meterskey',meterskey)
    const metersArr=[]
    for(let i=0;i<meterskey.length;i++){
      if(formValues[`meter_value-${meterskey[i]}`]&&formValues[`meter_date-${meterskey[i]}`]){
        metersArr.push({
          meter_number:this.state.editRecord.number,
          value:formValues[`meter_value-${meterskey[i]}`],
          date:moment(formValues[`meter_date-${meterskey[i]}`]).format('YYYY-MM-DD'),
        })
      }

    }
    console.log('metersArr',metersArr);
    if(metersArr.length===0){
      message.error('请输入日期和抄表读数')
      return
    }
    const that=this;
    this.props.dispatch({
      type: 'meters/addValue',
      payload: metersArr,
      callback() {
        message.success('机械表抄表成功');
        // that.setState({
        //   mechanicalModal: false,
        // });
      },
    });
  }
  handleAddOneMechanical2=()=>{
    const formValues = this.addOneMechanicalFormRef2.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    console.log('meterskey',meterskey)
    const metersArr=[]
    for(let i=0;i<meterskey.length;i++){
      if(formValues[`meter_value-${meterskey[i]}`]&&formValues[`meter_date-${meterskey[i]}`]){
        metersArr.push({
          meter_number:formValues.meter_number,
          value:formValues[`meter_value-${meterskey[i]}`],
          date:moment(formValues[`meter_date-${meterskey[i]}`]).format('YYYY-MM-DD'),
        })
      }

    }
    console.log('metersArr',metersArr);
    if(metersArr.length===0){
      message.error('请输入日期和抄表读数')
      return
    }
    const that=this;
    this.props.dispatch({
      type: 'meters/addValue',
      payload: metersArr,
      callback() {
        message.success('机械表抄表成功');
        // that.setState({
        //   mechanicalModal: false,
        // });
        that.addOneMechanicalFormRef2.props.form.resetFields();
        that.addOneMechanicalFormRef2.setState({
          meterDetail:{
            last_online_time:''
          }
        })
        document.querySelector(`.meter_number2 input`).focus()
      },
    });
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'meters/add',
      payload: {
        ...formValues,
        install_date: formValues.install_date ? moment(formValues.install_date).format('YYYY-MM-DD') : '',
      },
      callback() {
        message.success('添加水表成功');
        that.setState({
          addModal: false,
        });
        const {
          meters: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleAddDMA=()=>{
    const that=this
    const formValues = this.editDMAFormRef.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/meters/${this.state.editRecord.id}/join_area`, {
      method: 'PUT',
      data: {
        ...formValues
      },
    }).then((response) => {
      if (response.status === 200) {
        message.success('水表参与DMA设置成功')
        that.setState({
          editDMAModal:false
        })
        const {
          meters: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleFormReset = () => {
    const { form } = this.props;
    const username=sessionStorage.getItem('username')
    form.resetFields();
    let vendor_id='';
    if(username==='宁波水表'){
      vendor_id='274576011256434688'
    }else if(username==='竞达水表'){
      vendor_id='270602198973857792'
    }else if(username==='西安旌旗'){
      vendor_id='124590517324547876'
    }else if(username==='泰安水表'){
      vendor_id='124590517324752831'
    }else if(username==='泰安新贝水表'){
      vendor_id='364715278489198597'
    }
    this.handleSearch({
      company_ids:sessionStorage.getItem('company_sign'),
      number: '',
      user_number: '',
      valve_status:'',
      opened_account:'',
      caliber:'',
      address: '',
      vendor_id:vendor_id,
      communication_type:'',
      company_id:'',
      status:'1',
      page: 1,
      per_page: 50,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `meters/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        install_date: formValues.install_date ? moment(formValues.install_date).format('YYYY-MM-DD') : '',
      },
      callback() {
        message.success('修改水表成功');
        that.setState({
          editModal: false,
        });
        const {
          meters: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `meters/remove`,
      payload: { id },
      callback: () => {
        message.success('删除水表成功');
        const {
          meters: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '关';
        return <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={false}/>;
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '开';
        return <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={true}/>;
        break;
      case 2:
        type = 'close-circle', color = '#fe5810', text = '未上报';
        break;
      case 3:
        type = 'close-circle', color = '#fe1b2e', text = '异常';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      meters: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username');
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            meters: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '水表号',
        width: 150,
        frozen:true,
        key: 'number',

      },
      {
        name: '安装地址',
        frozen:true,
        key: 'address',
        width: 200,
      },
/*      {
        name: '口径',
        key: 'address',
        width: 100,
      },*/
      {
        name: '阀门状态',
        key: 'valve_status',
        width: 100,
        formatter: (event) => {
          return renderValveOpen(event.value,event.row.is_valve);
        },
      },
      {
        name: '水表厂商名称',
        key: 'vendor_name',
        width: 130,
      },
      {
        name: '协议名称',
        key: 'protocol_name',
        width: 150,
      },
      {
        name: '信号强度',
        key: 'signal_intensity',
        width: 80,
        formatter: (event) => {
          return renderSignalIntensity(event.value);
        },
      },
      {
        name: '最后一次上线时间',
        key: 'last_online_time',
        width: 160,
      },
      {
        name: '最新读值(m³)',
        key: 'latest_value',
        width: 100,
      },
      {
        name: '异常天数',
        key: 'abnormal_days',
        width: 100,
        formatter: (e) => {
          return <p
            className={(e.value>=7)? (e.value>=15)?'table-error table-status':'table-warm table-status' : ''}> {e.value}
          </p>;
        },
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            find(this.permissions, { name: 'meter_operation2' }) &&
            <Fragment>
              {/*{event.row.communication_type===2&&<Button
                type="primary"
                size="small"
                icon="setting"
                onClick={(e) => {
                  this.setState({
                    editRecord: event.row,
                    mechanicalModal: true,
                  });
                }
                }
              >机械抄表
              </Button>}*/}
              <Button
                type="primary"
                size="small"
                icon="edit"
                onClick={(e) => {
                  this.setState({
                    editRecord: event.row,
                    editModal: true,
                  });
                }
                }
              >编辑
              </Button>
              </Fragment>
            }
              {
                event.row.number.indexOf('#')<0&&  find(this.permissions, { name: 'meter_delete2' }) &&
                <Button
                  type="danger"
                  size="small"
                  icon="delete"
                  onClick={(e) => {
                    e.stopPropagation();
                    request(`/accounts`, {
                      method: 'GET',
                      params: {
                        meter_number: event.row.number,
                        communication_type: event.row.communication_type,
                      },
                    }).then((response) => {
                      if (response.status === 200) {
                        let isAccount=false
                        for(let i=0;i<response.data.data.length;i++){
                          if(response.data.data[i].meter_number===event.row.number){
                            isAccount=true
                          }
                        }
                        if(isAccount){
                          message.error('该水表已经开户，不能删除')
                        }else{
                          confirm({
                            title: `确定要删除水表"${event.row.number}"吗?`,
                            content: '删除后数据不可逆，请谨慎操作！',
                            okText: '确定',
                            okType: 'danger',
                            cancelText: '取消',
                            centered:true,
                            maskClosable: true,
                            onOk() {
                              that.handleDelete(event.row.id);
                            },
                            onCancel() {
                              console.log('Cancel');
                            },
                          });
                        }
                        return
                        if (response.data.data.length > 0) {

                        }else{

                        }
                      }


                    });

                  }
                  }
                >删除
                </Button>
              }




        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    if(username==='唐永臻'||username==='amwares'){
      columns.splice(7,0,{
        name: 'SNR',
        key: 'snr',
        width: 80,
        formatter: (event) => {
          return <p>{Number(event.value)===-1?'异常':event.value}</p>
        },
      },)
    }
    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>水表管理</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item  animated fadeInLeft">
            <p>水表总数量(个)</p>
            <h4>{meta.total}</h4>
          </div>

            <div size="large" className="table-info-right-item  animated fadeInRight">
              {
                find(this.permissions, {name: 'meter_add2'}) && <Button
                  icon="windows"
                  style={{marginLeft: 8}}
                  type="primary"
                  onClick={
                    () => {
                      this.setState({
                        importModal: true,
                      });
                    }
                  }
                >
                  批量导入水表
                </Button>
              }
              {
                find(this.permissions, {name: 'meter_add2'}) && <Button
                  icon="plus"
                  style={{marginLeft: 8}}
                  type="primary"
                  className={'btn-cyan'}
                  onClick={
                    () => {
                      this.setState({
                        addModal: true,
                      });
                    }
                  }
                >
                  添加水表
                </Button>
              }
              {
                find(this.permissions, {name: 'meter_operation2'}) &&
                <Button
                  icon="export"
                  style={{marginLeft: 8}}
                  type="primary"
                  onClick={
                    () => {
                      this.setState({
                        addMechanicalModal: true,
                      });
                    }
                  }
                >
                  远传表手工抄表
                </Button>
              }
              {/*
              <Button
                icon="setting"
                style={{ marginLeft: 8 }}
                type="primary"

                onClick={
                  () => {
                    this.setState({
                      mechanicalModal2: true,
                    },function(){
                      if(document.querySelector(`.meter_number2 input`)){
                        document.querySelector(`.meter_number2 input`).focus()
                      }

                    });
                  }
                }
              >
                单个手工抄表
              </Button>*/}
            </div>

        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (index,row) => {
                if (!row) {
                  return;
                }
                this.props.dispatch({
                  type: 'meters/changeSelectRow',
                  payload:[index],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          meters: {  scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop =0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`添加水表`}
        placement="right"
        onClose={() => {
          this.setState({
            addModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.addModal}
      >
        <AddOrEditMeter
          onClose={() => {
            this.setState({
              addModal: false,
              editRecord: {},
            });
          }}
          onSave={this.handleAdd}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
      <Drawer
        title={`修改水表 ${this.state.editRecord.number} `}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            editModal: false,
            editRecord: {},
          });
        }}
        width={700}
        visible={this.state.editModal}
      >
        <AddOrEditMeter
          onClose={() => {
            this.setState({
              editModal: false,
              editRecord: {},
            });
          }}
          editRecord={this.state.editRecord}
          onSave={this.handleEdit}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />
      </Drawer>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.importModal} modalClass="importModal" title="导入水表"/>}
        visible={this.state.importModal}
        centered
        onOk={this.handleAdd}
        className="importModal"
        onCancel={() => {
          this.setState({ importModal: false });
        }}

      >
        <ImportMeter findChildFunc={this.findChildFunc} wrappedComponentRef={(inst) => this.importFormRef = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editDMAModal} modalClass="editDMAModal"
                                title={`${this.state.editRecord.number} DMA统计设置`}/>}
        visible={this.state.editDMAModal}
        destroyOnClose
        centered
        onOk={this.handleAddDMA}
        className="editDMAModal"
        onCancel={() => {
          this.setState({ editDMAModal: false });
        }}

      >
        <EditDMA type={"meter"} editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.editDMAFormRef = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.addMechanicalModal} modalClass="addMechanicalModal" title="批量手工抄表"/>}
        visible={this.state.addMechanicalModal}
        centered
        onOk={()=>{
          confirm({
            title: `确定要手工添加水表读数吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'primary',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleAddMechanical()
              // that.handleDelete(event.row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
        className="addMechanicalModal"
        width={1140}
        onCancel={() => {
          this.setState({ addMechanicalModal: false });
        }}

      >
        <AddMechanical  wrappedComponentRef={(inst) => this.addMechanicalFormRef = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.mechanicalModal} modalClass="mechanicalModal"
                                title={`机械表 ${this.state.editRecord.number} 抄表`}/>}
        visible={this.state.mechanicalModal}
        centered
        destroyOnClose
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onOk={()=>{
          confirm({
            title: `确定要手工添加机械水表读数吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'primary',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleAddOneMechanical()
              // that.handleDelete(event.row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
        className="mechanicalModal"
        width={700}
        onCancel={() => {
          this.setState({ mechanicalModal: false });
        }}

      >
        <AddOneMechanical handleAddOneMechanical={this.handleAddOneMechanical}  meter_number={this.state.editRecord.number}  editRecord={this.state.editRecord}  wrappedComponentRef={(inst) => this.addOneMechanicalFormRef = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.importModal} modalClass="importModal" title="批量导入水表"/>}
        visible={this.state.importModal}
        centered
        onOk={this.handleImport}
        className="importModal"
        onCancel={() => {
          this.setState({ importModal: false });
        }}

      >
        <ImportMeter findChildFunc={this.findChildFunc} wrappedComponentRef={(inst) => this.importFormRef = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.mechanicalModal2} modalClass="mechanicalModal2" title="单个手工抄表"/>}
        visible={this.state.mechanicalModal2}
        centered
        onOk={()=>{
          confirm({
            title: `确定要手工添加水表读数吗?`,
            content: '请谨慎操作！',
            okText: '确定',
            okType: 'primary',
            cancelText: '取消',
            centered:true,
            maskClosable: true,
            onOk() {
              that.handleAddOneMechanical2()
              // that.handleDelete(event.row.id);
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
        className="mechanicalModal2"
        width={700}
        onCancel={() => {
          this.setState({ mechanicalModal2: false });
        }}

      >
        <AddOneMechanical2 handleAddOneMechanical2={this.handleAddOneMechanical2} wrappedComponentRef={(inst) => this.addOneMechanicalFormRef2 = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
